package com.yj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yj.mapper.UserMapper;
import com.yj.po.User;
import com.yj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService,UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserMapper userMapper;


    /**
     * 加载用户信息包括角色信息权限信息
     *
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findUserByUserName(username);

        if (user == null) {
            throw new UsernameNotFoundException(username);
        }

        List<Map<String,String>> roles = userMapper.findUserRoleMenuByUserName(username);

        List<String> authorityList = roles.stream().map(r -> "role::" + r.get("permission")).collect(Collectors.toList());
        user.setAuthorities( AuthorityUtils.commaSeparatedStringToAuthorityList(
                String.join(",",authorityList)
        ));

        return user;
    }


    @Override
    public boolean addUser(User user) {
        Assert.notNull(user, "user cannot be null");
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return this.save(user);
    }

    @Override
    public User login(User user) {
        Assert.notNull(user, "user cannot be null");
        String username = user.getUsername();
        Assert.notNull(username, "username cannot be null");
        String password = user.getPassword();
        Assert.notNull(password, "password cannot be null");

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);

        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null) {
            throw new RuntimeException("username or password not valid");
        }
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        User result = (User) authenticate.getPrincipal();
        return result;
    }
}
